﻿using AVCUMPlatform.Entities;
using AVCUMPlatform.HelperLibrary;
using AVCUMPlatform.MiniWXService.Model;
using Newtonsoft.Json;

namespace AVCUMPlatform.MiniWXService.Service
{
    /// <summary>
    /// 微信接口访问工具类
    /// </summary>
    public class MiniWXService : IMiniWXPlatformApiHelper
    {
        /// <summary>
        /// 公众号appid
        /// </summary>
        private string _appid { get; set; }
        /// <summary>
        /// 公众号appSecret
        /// </summary>
        private string _appSecret { get; set; }
        /// <summary>
        /// 小程序appid
        /// </summary>
        private string _miniwxappid { get; set; }
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appSecret"></param>
        /// <param name="miniwxappid"></param>
        public MiniWXService(string appid, string appSecret, string miniwxappid)
        {
            _appid = appid;
            _appSecret = appSecret;
            _miniwxappid = miniwxappid;
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public SendTemplateMsgRes SendTemplateMsg(MiniWXTemplateMsgRM data)
        {
            try
            {
                //Log.Write($"requestParam:{JsonConvert.SerializeObject(data)}");
                string token = MiniWXToken.GetInstance(_appid, _appSecret).AccessToken;
                string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
                SendTemplateMsgRes sendTemplateMsgRes = HTTPHelper.Post<SendTemplateMsgRes>(url, data);
                if (sendTemplateMsgRes.msgid == null)
                {
                    token = MiniWXToken.GetInstance(_appid, _appSecret).RefreshToken();
                    url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
                    sendTemplateMsgRes = HTTPHelper.Post<SendTemplateMsgRes>(url, data);
                }
                return sendTemplateMsgRes;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有微信消息模板
        /// </summary>
        /// <returns></returns>
        public AllPrivateTemplates GetAllPrivateTemplate()
        {
            try
            {
                string token = MiniWXToken.GetInstance(_appid, _appSecret).AccessToken;
                string url = $"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={token}";
                return HTTPHelper.Get<AllPrivateTemplates>(url);
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                return null;
            }
        }
    }
}